package Util;

import java.nio.charset.Charset;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 使用DES无填充的方式加密和解密。
 * @author GuoZeXin
 *
 */
public class Crypto2 {

	/**
	 * 只能用8个字节的秘钥
	 */
	private String key = "WeakBird";
	private String charSet = "utf-8";
	private byte[] raw = key.getBytes(Charset.forName(charSet));
	private SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");


	/**
	 * 加密，返回Byte类型
	 * @author GuoZeXin
	 * @version 2.0.1
	 * 
	 * @created 2014.12.11
	 * @latest 2014.12.11
	 * 
	 * @param value
	 * @return
	 */
	public byte[] encrypt(byte[] value) {
		try {
			Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
			byte ret[]= cipher.doFinal(value);
			return ret;
		} catch(Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 解密，返回Byte类型
	 * @author GuoZeXin
	 * @version 2.0.1
	 * 
	 * @created 2014.12.11
	 * @latest 2014.12.11
	 * @param encrypted
	 * @return
	 */
	public byte[] decrypt(byte[] encrypted) {
		try {
			Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);
			byte[] original = cipher.doFinal(encrypted);
			return original;
		} catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
